package com.rocching.easychat.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.rocching.easychat.R;
import com.rocching.easychat.adapter.GroupListAdapter;
import com.rocching.easychat.core.IApiCallback;
import com.rocching.easychat.core.ViewClickListener;
import com.rocching.easychat.model.GroupListModel;
import com.rocching.easychat.model.MyGroupListModel;
import com.rocching.easychat.service.GroupService;
import com.rocching.easychat.util.AppUtil;

import java.util.List;

import io.rong.imkit.utils.RouteUtils;
import io.rong.imlib.model.Conversation;

public class GroupListActivity extends AppCompatActivity {
    private final String TAG = GroupListActivity.class.getName();

    private GroupListAdapter groupListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_list);

        init();
    }

    private void init() {
        ListView listView = findViewById(R.id.group_list);
        groupListAdapter = new GroupListAdapter(this);
        listView.setAdapter(groupListAdapter);

        listView.setOnItemClickListener(new ViewClickListener() {
            @Override
            public void onDItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                GroupListModel model = (GroupListModel) listView.getItemAtPosition(i);

                handleClick(model);
            }
        });

        initData();
    }

    private void initData() {
        GroupService.getInstance().getMyGroupList(new IApiCallback<MyGroupListModel>() {
            @Override
            public void onResponse(boolean succeeded, String body, MyGroupListModel data) {
                if (succeeded) {
                    updateView(data.getList());
                }
            }
        });
    }

    private void updateView(List<GroupListModel> list) {
        if (groupListAdapter != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    groupListAdapter.update(list);
                }
            });
        }
    }

    private void handleClick(GroupListModel model) {
        try {
            RouteUtils.routeToConversationActivity(this, Conversation.ConversationType.GROUP, AppUtil.getGroupId(model.getId()));
            finish();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
}